package moriarty.gwt.server;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

public class XMPPSender {

	private JID jid;
	private String msg;
	
	XMPPSender(JID jid, String msg){
		this.jid = jid;
		this.msg = msg;
	}
	
	/**
	 * Tries to send a message to a JID using XMPP
	 * If it fails, it will attempt to send an invitation. The message will NOT come in
	 * when the invitation is accepted.  
	 * TODO: Implement something that tried to re-send once invitation is accepted
	 * @param jid - JID of user to try to send instant message to
	 * @param msg - The message you wish to send to a JID
	 */
	public String send(){
        Message xmppmsg = new MessageBuilder()
        .withRecipientJids(jid)
        .withFromJid(new JID("sotdbot@appspot.com"))
        .withBody(msg)
        .build();

        boolean messageSent = false;
        XMPPService xmpp = XMPPServiceFactory.getXMPPService();
        SendResponse status = xmpp.sendMessage(xmppmsg);
        messageSent = (status.getStatusMap().get(jid) == SendResponse.Status.SUCCESS);
		
        if (!messageSent) {
        	xmpp.sendInvitation(jid, new JID("sotdbot@appspot.com"));
        	return jid.getId();
        }
        else{
        	return "";
        }
	}

	public JID getJid() {
		return jid;
	}

	public String getMsg() {
		return msg;
	}
}
